import { Button, Input, Table } from 'antd';
import { useRef, useState } from 'react';
import * as XLSX from 'xlsx';

const columns = [
  {
    title: '姓名',
    dataIndex: 'name',
  },
  {
    title: '年龄',
    dataIndex: 'age',
  },
];

const Index = () => {
  const ipt: any = useRef();
  const [dataSource, setDataSource] = useState<any>([]);

  const exportFile = () => {
    ipt.current.input.click();
  };

  const handleChange = () => {
    const file = ipt.current.input.files[0];

    const render = new FileReader();
    render.readAsBinaryString(file);
    render.onload = () => {
      // 将拿到的文件转成数据流
      const book = XLSX.read(render.result, { type: 'binary' });
      // 导入哪一张表
      const res = book.Sheets['Sheet1'];
      const result = XLSX.utils.sheet_to_json(res);
      console.log(result);
      setDataSource(result);
    };
  };

  return (
    <>
      <h2>文件导入</h2>
      <Button onClick={exportFile}>导入</Button>
      <Input
        type="file"
        ref={ipt}
        style={{ display: 'none' }}
        onChange={handleChange}
      />
      <Table dataSource={dataSource} columns={columns}></Table>
    </>
  );
};

export default Index;
